<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../../css/public.css" media="all">
    <style>
        body {
            background-color: #ffffff;
        }
    </style>
</head>
<body>
<div class="layui-form layuimini-form">
    <div class="layui-form-item">
        <label class="layui-form-label required">接收者ID</label>
        <div class="layui-input-block">
            <input type="text" name="sendTo" lay-verify="required" lay-reqtext="接收者ID不能为空" placeholder="请输入用户id"
                   value=""
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">手机号码</label>
        <div class="layui-input-block">
            <input type="text" name="phoneNumber" lay-verify="required" lay-reqtext="手机号码不能为空" placeholder="请输入手机号码"
                   value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">短信模板</label>
        <div class="layui-input-block">
            <select name="templateCode" lay-filter="templateCode" lay-reqtext="模板不能为空">
                <option value="">请选择模板</option>
            </select>
        </div>
    </div>
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 10px;">
        <legend>模板参数</legend>
    </fieldset>
    <div class="layui-form-item">
        <div class="input-container">
            <table class="layui-table">
                <colgroup>
                    <col width="120">
                    <col>
                </colgroup>
                <thead>
                <tr>
                    <th>变量名</th>
                    <th>变量值</th>
                </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">提交</button>
        </div>
    </div>
</div>
<script src="../../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="../../../lib/common/common.js" charset="utf-8"></script>
<script src="../../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="../../../js/lay-module/xm-select-master/dist/xm-select.js" charset="utf-8"></script>
<script>

    let codeList = [];

    window.onload = function () {
        $.ajax({
            type: "GET",
            url: '/sms/template/list',
            dataType: 'json',
            contentType: 'application/x-www-form-urlencoded',
            success: function (req) {
                if (req.code === '200') {
                    let templateList = req.data
                    if (templateList.length > 0) {
                        layui.use(['layer', 'form'], function () {
                            var form = layui.form,
                                layer = layui.layer,
                                $ = layui.$;
                            let options = "";
                            for (const index in templateList) {
                                options += "<option value='" + templateList[index].templateId + "'>" + templateList[index].name + "</option>";
                            }
                            $("select[name='templateCode']").append(options);// 重新渲染下拉框
                            form.render('select');
                        });

                    } else {
                        layer.msg('请先录入短信模板');
                        setTimeout(function () {
                            let iframeIndex = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(iframeIndex);
                        }, 1500);
                    }
                } else {
                    layer.msg(req.msg);
                    setTimeout(function () {
                        let iframeIndex = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(iframeIndex);
                    }, 1500);
                }
            },
            error: function (e) {
                layer.msg("数据异常");
                setTimeout(function () {
                    let iframeIndex = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(iframeIndex);
                }, 1500);
            }
        })
    }

    layui.use(['layer', 'form', 'layarea'], function () {
        var form = layui.form,
            layer = layui.layer,
            $ = layui.$;

        form.on('select(templateCode)', function (data) {
            // 监听下拉框
            if (isNotNull(data.value)) {
                $.ajax({
                    type: "GET",
                    url: '/sms/' + data.value + '/findTemplate/',
                    dataType: 'json',
                    contentType: 'application/x-www-form-urlencoded',
                    success: function (req) {
                        if (req.code === '200') {
                            let content = req.data?.content;
                            // 通过正则去去取出占位符的变量
                            let reg = /\${(.+?)}/g;
                            let match = [];
                            // 清空数据
                            codeList = [];
                            while ((match = reg.exec(content)) !== null) {
                                codeList.push(match[1]);
                            }
                            var tableHtml = '<table class="layui-table">'
                                + '<colgroup>'
                                + '<col width="120">'
                                + '<col>'
                                + '</colgroup>'
                                + '<thead>'
                                + '<tr>'
                                + '<th>变量名</th>'
                                + '<th>变量值</th>'
                                + '</tr>'
                                + '</thead>'
                                + '<tbody>';
                            codeList.forEach(function (code) {
                                tableHtml += '<tr>'
                                    + '<td>' + code + '</td>'
                                    + '<td><input type="text" name="' + code + '" lay-verify="required" class="layui-input"></td>'
                                    + '</tr>';
                            });
                            tableHtml += '</tbody>'
                                + '</table>';
                            // 将表格添加到页面中
                            $('.input-container').empty().append(tableHtml);
                            // 重新渲染表单
                            layui.form.render();
                        } else {
                            layer.msg(req.msg);
                        }
                    },
                    error: function (e) {
                        layer.msg("获取模板参数失败");
                    }
                })
            }

        })

        //监听提交
        form.on('submit(saveBtn)', function (data) {
            if (codeList.length <= 0) {
                layer.msg("请将模板参数变量填写完成");
            }
            var index = layer.alert("确定提交吗？", {
                title: '提示'
            }, function () {
                let myMsg = layer.msg("正在提交...", {
                    icon: 16,
                    time: -1
                })
                console.log(codeList)
                console.log(data.field)
                let templateParam = {}
                codeList.forEach(function (variable) {
                    templateParam[variable] = data.field[variable];
                });
                const requestData = {
                    sendTo: data.field.sendTo,
                    phoneNumber: data.field.phoneNumber,
                    templateCode: data.field.templateCode,
                    templateParam: JSON.stringify(templateParam),
                }
                $.ajax({
                    type: "post",
                    url: '/sms/send',
                    data: JSON.stringify(requestData),
                    dataType: 'json',
                    contentType: 'application/json; charset=UTF-8',
                    success: function (req) {
                        if (req.code === '200') {
                            layer.msg("发送成功");
                            layer.close(index);
                            // 关闭弹出层
                            setTimeout(function () {
                                layer.close(myMsg);//手动关闭
                                let iframeIndex = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(iframeIndex);
                            }, 1500);
                        } else {
                            layer.msg(req.msg);
                            layer.close(myMsg);//手动关闭
                        }
                    },
                    error: function (e) {
                        layer.msg("发送失败");
                        layer.close(myMsg);//手动关闭
                    }
                })

            });

            return false;
        });

    });
</script>
</body>
</html>
